import { ref } from 'vue';
import Taro from '@tarojs/taro';

/**
 * 用户信息接口
 */
export interface NurseUser {
    id: string;
    name: string;
    defaultHospital: string;
    defaultHospitalName: string;
    defaultHospitalLatitude?: number;
    defaultHospitalLongitude?: number;
    nurseUserAddrList?: any[];
    nurseUserFamilyList?: any[];
}

/**
 * 用户服务
 */
export class UserService {
    /**
     * 获取当前用户信息
     */
    static getCurrentUser(): NurseUser | null {
        try {
            const userStr = Taro.getStorageSync('nurseUser');
            if (userStr) {
                const user = JSON.parse(userStr);
                return user.value || user; // 兼容不同存储格式
            }
            return null;
        } catch (error) {
            // console.error('获取用户信息失败:', error);
            return null;
        }
    }

    /**
     * 设置当前用户信息
     */
    static setCurrentUser(user: NurseUser): void {
        try {
            Taro.setStorageSync('nurseUser', JSON.stringify({ value: user }));
        } catch (error) {
            // console.error('设置用户信息失败:', error);
        }
    }

    /**
     * 更新用户默认医院
     */
    static updateDefaultHospital(hospitalId: string, hospitalName: string): void {
        try {
            const user = this.getCurrentUser();
            if (user) {
                user.defaultHospital = hospitalId;
                user.defaultHospitalName = hospitalName;
                this.setCurrentUser(user);
            }
        } catch (error) {
            // console.error('更新用户默认医院失败:', error);
        }
    }
}

/**
 * 模拟用户状态管理
 */
export function useAuthStore() {
    const nurseUser = ref<NurseUser | null>(UserService.getCurrentUser());

    const updateUser = (user: NurseUser) => {
        UserService.setCurrentUser(user);
        nurseUser.value = user;
    };

    return {
        nurseUser,
        updateUser
    };
}
